package xxy.com.customview;

import android.app.ActivityOptions;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.PersistableBundle;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.BounceInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import xxy.com.customview.modle.UserPacelable;
import xxy.com.customview.modle.UserSerializable;

import static android.view.animation.Animation.INFINITE;

public class MainActivity extends AppCompatActivity {

    private TextView tv;
    private Button button;
    private Animation animation;
    private AlphaAnimation alpha;

    public final static int RETURN_OK = 3;
    public final static int REQUEST_CODE = 1;
    private ConstraintLayout constraintlayout;
    private Button goToButton;

    private final String INTENT_TIME = "时间";
    private ObjectOutputStream objectOutputStream;
    private final String FILE_NAME = "d.txt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.e("Life", "main1_onCreate");
        init();
        initView();
    }

    public void init() {
        tv = (TextView) findViewById(R.id.main_tv);
        button = (Button) findViewById(R.id.main_button);
        goToButton = (Button) findViewById(R.id.main_butt_beginAnim);
        constraintlayout = (ConstraintLayout) findViewById(R.id.main_constraintlagyout);

        //测试serializable 写入部分
        try {
            File file = new File(getFilesDir(), FILE_NAME);
            Log.e("serializable", "" + file.getAbsolutePath());
            objectOutputStream = new ObjectOutputStream(new FileOutputStream(file));
            UserSerializable iverson = new UserSerializable(24, "Kobe 科比", "8号 24号 球衣");
            UserPacelable kobe = new UserPacelable(24, "Jordan 乔丹", "23号  球衣");
            objectOutputStream.writeObject(iverson);
            objectOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("serializable", "写入失败");
        }
    }

    private void initView() {
        //一系列动画集合
        animation = AnimationUtils.loadAnimation(this, R.anim.viewanimation_set);
        button.startAnimation(animation);

        RotateAnimation rotateAnim = (RotateAnimation) AnimationUtils.loadAnimation(this, R.anim.viewanimation_rotate);
//        button.startAnimation(rotateAnim);

        //透明度动画
        AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
        alphaAnimation.setDuration(1000);
        alphaAnimation.setRepeatCount(INFINITE);
//        tv.startAnimation(alphaAnimation);

        //旋转动画
        RotateAnimation rotateAnimation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setDuration(2000);
        rotateAnimation.setRepeatCount(INFINITE);
        rotateAnimation.setRepeatMode(Animation.RESTART);
        rotateAnimation.setStartOffset(500);
        rotateAnimation.setInterpolator(new BounceInterpolator());
//        button.startAnimation(rotateAnimation);

        //透明度动画
        alpha = (AlphaAnimation) AnimationUtils.loadAnimation(this, R.anim.viewanimation_alpha);
        alpha.setRepeatMode(Animation.RESTART);
        alpha.setRepeatCount(INFINITE);
        alpha.setDuration(2000);
        tv.startAnimation(alpha);
    }

    /**
     * 点击监听
     *
     * @param view
     */
    public void beginAnim(View view) {
        switch (view.getId()) {
            case R.id.main_butt_beginAnim:   //启动第二个activity并且在第二个activity退出时希望有东西返回， REQUEST_CODE 标识了是启动 Main2Activity 防止和其他activity搞混
                //老版本的转场动画
//                startActivityForResult(new Intent(this, Main2Activity.class),REQUEST_CODE);
//                overridePendingTransition(R.anim.transiton_in,R.anim.transiton_out);

                //Android 5.0 后的转场动画
                //1、自定义转场动画
//                ActivityOptionsCompat activityOptionsCompat = ActivityOptionsCompat.makeCustomAnimation(this, R.anim.transiton_in, R.anim.transiton_out);
//                ActivityCompat.startActivityForResult(this,new Intent(this, Main2Activity.class),REQUEST_CODE, activityOptionsCompat.toBundle());
                //2、makeScaleUpAnimation
//                ActivityOptionsCompat makeScaleUpAnimation = ActivityOptionsCompat.makeScaleUpAnimation(constraintlayout, constraintlayout.getWidth() / 2, constraintlayout.getHeight() / 2, 0, 0);
//                ActivityCompat.startActivityForResult(this, new Intent(this, Main2Activ ity.class),REQUEST_CODE, makeScaleUpAnimation.toBundle());
                //3、makeSceneTransitionAnimation
//                ActivityOptionsCompat makeSceneTransitionAnimation = ActivityOptionsCompat.makeSceneTransitionAnimation(this, constraintlayout, getString(R.string.transition_scene_view));
//                ActivityCompat.startActivityForResult(this, new Intent(this, Main2Activity.class),REQUEST_CODE, makeSceneTransitionAnimation.toBundle());
                //4、定义转场和过渡动画的xml  进场：explode 出场：fade
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    // 我们这里没有用ActivityCompat转场
                    startActivityForResult(new Intent(this, Main2Activity.class), REQUEST_CODE, ActivityOptions.makeSceneTransitionAnimation(this).toBundle());
                }
                break;

            case R.id.main_fab:   //悬浮按钮 snackbar
                Snackbar.make(findViewById(R.id.main_fab), "测试隐式Intent？", Snackbar.LENGTH_SHORT)
                        .setAction("启动", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //测试隐式Intent
                                PackageManager packageManager = MainActivity.this.getPackageManager();
                                Intent intent = new Intent("xxy.com.customview.Iverson");
                                intent.addCategory("xxy.com.customview.xxy");
                                if (packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {   //判断是否有隐式注册的intent filter，以防出现bug
                                    startActivity(intent);
                                }
                            }
                        })
                        .show();
                break;
            case R.id.main_button:   //回旋镖动画

                //测试Serializable 读取部分
                try {
                    ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(getFilesDir() + File.separator + FILE_NAME));   //拿到数据就要找到创建好的文件的路径，/data/user/0/xxy.com.customview/files/c.txt
                    UserSerializable user = (UserSerializable) objectInputStream.readObject();
//                    UserPacelable user = (UserPacelable) objectInputStream.readObject();
                    objectInputStream.close();
                    Log.e("serializable", "UserSerializable : \t" + user.getName() + "\t" + user.getPhone() + "\n" + getFilesDir());
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e("serializable", "读取失败");
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                    Log.e("serializable", "读取类转换异常");
                }

                button.startAnimation(animation);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Toast.makeText(this, "onNewIntent", Toast.LENGTH_SHORT).show();
        Log.e("Life", "main1_onNewIntent");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.e("Life", "main1_onRestart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("Life", "main1_onResume");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.e("Life", "main1_onRestoreInstanceState");
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        Log.e("Life", "main1_onSaveInstanceState");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("Life", "main1_onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e("Life", "main1_onStop");
    }

    /**
     * 从之前一个acitivty退出之后返回的东西
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RETURN_OK && data != null) {
            tv.setText(data.getStringExtra("test"));
            tv.setTextColor(getResources().getColor(R.color.colorAccent));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (alpha != null) {
            alpha.reset();
        }

        Log.e("Life", "main1_onDestroy");
    }
}
